package com.ba.grain;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Node;

import util.RequestResponse;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Toast;

public class ReportActivity extends RecordActivity {

	/**
	 * 要上报的一项的key
	 */
	public static final String KEY_REPORT_ITEM_KEY = "key_report_item_key";
	public static final String KEY_REPORT_FILE_PATH = "key_report_file_path";
	private ProgressDialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDialog = new ProgressDialog(this);
		mDialog.setCancelable(false);
		reportFromIntent();
		mBtn.setText("上报");
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		if (v == mBtn) {
			SparseBooleanArray sba = getListView().getCheckedItemPositions();
			List<ListItem> items = new ArrayList<ListItem>();
			for (int i = 0; i < sba.size(); i++) {
				int key = sba.keyAt(i);
				if (sba.get(key)) {
					ListItem li = (ListItem) getListView().getItemAtPosition(key);
					if (li.isUploaded()) {
						continue;
					}
					items.add(li);
				}
			}

			ListItem[] arr = new ListItem[items.size()];
			for (int i = 0; i < arr.length; i++) {
				arr[i] = items.get(i);
			}
			if (arr.length == 0) {
				Toast.makeText(this, "没有需要上报的数据", Toast.LENGTH_SHORT).show();
			} else
				doReport(null, arr);
		}
		super.onClick(v);
	}

	private void doReport(final String filePath, final ListItem... items) {

		mDialog.setMessage("上报中...");
		mDialog.show();
		new Thread() {
			@Override
			public void run() {
				super.run();
				int serinum = (int) System.currentTimeMillis();
				String[] attr = new String[] { "site_id", "serinum", "foodType_id", "grade_id",
						"buyPrice", "tradePrice", "dayRetailPrice", "weekRetailPrice" };
				String[][] values = new String[items.length][attr.length];
				for (int i = 0; i < items.length; i++) {
					values[i][0] = String.valueOf(items[i].site_id);
					values[i][1] = String.valueOf(serinum);
					values[i][2] = String.valueOf(items[i].foodType_id);
					values[i][3] = String.valueOf(items[i].grade_id);
					values[i][4] = String.valueOf(items[i].buyPrice);
					values[i][5] = String.valueOf(items[i].tradePrice);
					values[i][6] = String.valueOf(items[i].dayRetailPrice);
					values[i][7] = String.valueOf(items[i].weekRetailPrice);
				}
				final Node[] node = new Node[1];
				FileInputStream is = null;
				String fileName = null;
				if (filePath != null) {
					File f = new File(filePath);
					fileName = f.getName();
					try {
						is = new FileInputStream(filePath);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				final int result = RequestResponse.excuteInsert(G.sSocket, "tail_quotation", attr,
						values, fileName, is, serinum, node);
				final FileInputStream theFis = is;
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						if (null != theFis) {
							try {
								theFis.close();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						mDialog.dismiss();
						if (result == 0) {
							Toast.makeText(ReportActivity.this,
									String.format("成功上报了%d项记录", items.length), Toast.LENGTH_SHORT)
									.show();
							for (ListItem listItem : items) {
								listItem.mUploaded = true;
							}
							CollectActivity.doSave(ReportActivity.this, items);
							DataUploadAdapter dua = (DataUploadAdapter) getListAdapter();
							dua.notifyDataSetChanged();
						} else {
							Toast.makeText(ReportActivity.this,
									String.format("%s(%d)", "上传未成功", result), Toast.LENGTH_SHORT)
									.show();
						}
					}
				});
			}

		}.start();
	}

	private void reportFromIntent() {
		String key = getIntent().getStringExtra(KEY_REPORT_ITEM_KEY);
		if (key != null) {
			String filePath = getIntent().getStringExtra(KEY_REPORT_FILE_PATH);
			ListItem item = null;
			for (int i = 0; i < getListAdapter().getCount(); i++) {
				ListItem li = (ListItem) getListAdapter().getItem(i);
				if (key.equals(li.key)) {
					item = li;
				}
			}
			if (item == null) {
				return;
			}
			doReport(filePath, item);
		}
	}

}
